//
//  OAuthViewController.swift
//  swiftImitationWeibo
//
//  Created by 杨果果 on 16/7/10.
//  Copyright © 2016年 yang. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
//APPkey
//let weiboAPPKey = "2733039189"
let weiboAPPKey = "1182785320"
//安全码
let weiboAPPSecret = "1606843f6c67acf9cd0771db17fc1ac2"
//let weiboAPPSecret = "54e8fbb7d1cc63a4cee879949fe838a8"

//回调页面(成功登录之后跳转的页面)
//let weiboRedirect_Uri = "http://baidu.com"
let weiboRedirect_Uri = "http://www.itcast.cn"
//  切换根视图控制器通知名
let SwitchRootVCNotification = "SwitchRootVCNotification"
class OAuthViewController: UIViewController {
    
    //创建界面
    private lazy var webView: UIWebView = UIWebView()
    override func loadView() {
        webView.delegate = self
        webView.opaque = false
        view = webView
    }
    
    //button
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        requestOAuthLogin()
        setupNav()
    }
    private func requestOAuthLogin() {
        //创建url
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(weiboAPPKey)&redirect_uri=\(weiboRedirect_Uri)"
//        print(url)
        //创建请求
        let request = NSURLRequest(URL: NSURL(string: url)!)
        //webView 添加请求
        webView.loadRequest(request)
    }
    
    private func setupNav() {
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cencelButtonAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
    }
    //取消
    @objc private func cencelButtonAction() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    //自动填充
    @objc private func autoFillAction() {

        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'hao123guohaibin@163.com'; document.getElementById('passwd').value = 'guohaibin012'")
    }
        
    
    
    
    
    
    
    
    
    
    
    
}
extension OAuthViewController: UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //如果url不存在  结束
        guard let url = request.URL else{
            return false
        }
        //此时url有值
        //获取url的绝对地址   如果不是之前设定的不管
        if !url.absoluteString.hasPrefix(weiboRedirect_Uri) {
            return true
        }
        // url是之前设定的 截取code
        if let query = url.query where query.hasPrefix("code=") {
            let code = query.substringFromIndex("code=".endIndex)
//            print("我想要的code" + code)
//            requestAccesstoken(code)
            UserAccountViewModel.sharedUserAccountViewModel.requestAccesstoken(code, callBack: { (isSuccess) -> () in
                if isSuccess {
                    print("登陆成功")
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //发送通知
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                } else {
                   print("登陆失败")
                }
                
            })
        }else{
            dismissViewControllerAnimated(true, completion: nil)
        }
        return false

    }
    func webViewDidStartLoad(webView: UIWebView) {

        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {

        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}

















